package info.emamian.droplet.provider;

import info.emamian.droplet.data.DynamoDbSms;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class TwilioAdaptor implements InputSMSAdaptor {
	private static final Logger logger = LoggerFactory.getLogger(TwilioAdaptor.class);
	private static final String PROVIDER_NAME = "twilio.com";

	public TwilioAdaptor() {
	}

	@Override
	public DynamoDbSms convertToDynamoDbSMS(HttpServletRequest request) {
		DynamoDbSms incoming = convertHttpRequestToDynamoDbSMS(request);
		return incoming;
	}

	private DynamoDbSms convertHttpRequestToDynamoDbSMS(HttpServletRequest request) {
		// debug
		if (logger.isDebugEnabled()) {
			try {
				Enumeration<?> headerNames = request.getHeaderNames();
				logger.debug("Headers:");
				while (headerNames.hasMoreElements()) {
					String hname = (String) headerNames.nextElement();
					if (hname == null)
						continue;
					logger.debug(" - [{}] -> [{}]", hname, request.getHeader(hname).toString());
				}
			}
			catch (Exception e) {
				logger.error("Exception , ", e);
			}
		}
		Map<String, String> properties = new HashMap<String, String>();

		try {
			// store header requests in properties
			Enumeration<?> c = request.getParameterNames();
			while (c.hasMoreElements()) {
				String el = (String) c.nextElement();
				if (el == null)
					continue;
				properties.put(el.toString(), request.getParameter(el));
				logger.debug("request param [{}] -> [{}]", el, request.getParameter(el));
			}
		}
		catch (Exception e) {
			logger.error("Exception , ", e);
		}
		properties.put("remoteAddr", request.getRemoteAddr());
		// extract sms properties
		String from = request.getParameter("From");
		String to = request.getParameter("To");
		String body = request.getParameter("Body");
		DynamoDbSms incomingSMS = new DynamoDbSms(from, to, body, getProviderName(), new Date(), true, properties);
		logger.debug("TwilioAdaptor converted from request : {}", incomingSMS);
		return incomingSMS;
	}

	@Override
	public String getProviderName() {
		return PROVIDER_NAME;
	}
}
